package com.example.sxmall.service.action.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.sxmall.auth.Authentication;
import com.example.sxmall.auth.UserInfo;
import com.example.sxmall.controller.shopCart.GlobalConstant;
import com.example.sxmall.controller.shopCart.vo.ProductVO;
import com.example.sxmall.controller.shopCart.vo.ShopCartVO;
import com.example.sxmall.controller.shopCart.vo.StoreProductVO;
import com.example.sxmall.exception.AppException;
import com.example.sxmall.redis.ShopCartKey;
import com.example.sxmall.service.ShopCartService;
import com.example.sxmall.service.action.ActionCartService;
import com.example.sxmall.service.dto.OperateCartDTO;
import com.example.sxmall.service.dto.ShopCartDTO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: TODO
 * @Author whh-yt
 * @Date 2022/3/17 4:30 下午
 */
@Service
public class RemoveCartActionService extends ActionCartService {

    @Override
    public ShopCartVO execute(OperateCartDTO operateCartDTO) {
        UserInfo userInfo = Authentication.getUserInfo();
        Long storeId = operateCartDTO.getStoreId();
        // 需要删除的商品
        ProductVO productVO = operateCartDTO.getProduct();
        if (Objects.isNull(productVO)) {
            throw new AppException(GlobalConstant.NETWORK_ERROR);
        }
        ShopCartDTO shopCartCache = redisService.get(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), ShopCartDTO.class);
        if (Objects.isNull(shopCartCache)) {
            ShopCartVO shopCartVO = new ShopCartVO();
            shopCartVO.setVersion(ShopCartService.SHOPCART_VERSION);
            shopCartVO.setStoreProductList(new ArrayList<>());
            shopCartVO.setInvalidProductList(new ArrayList<>());
            shopCartVO.setPaymentAmount("");
            return shopCartVO;
        }
        List<StoreProductVO> storeProductList = shopCartCache.getStoreProductList();
        storeProductList.forEach(storeProductVO -> {
            storeProductVO.getProductList().removeIf(item -> item.getSkuCode().equals(productVO.getSkuCode()));
        });
        storeProductList.removeIf(item -> CollectionUtils.isEmpty(item.getProductList()));
        if (CollectionUtils.isEmpty(storeProductList)) {
            redisService.delete(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId());
        } else {
            redisService.set(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), shopCartCache);
        }
        return super.execute(operateCartDTO);
    }
}
